package 剑指Offer.medium;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class 字符串的排列 {

    class Solution {
        public String[] permutation(String s) {
            char[] strings = s.toCharArray();

            List<String> res = new ArrayList<>();
            dfs(0, strings, res);
            return res.toArray(new String[res.size()]);
        }

        private void dfs(int depth, char[] strings, List<String> res) {
            //递归终止条件
            if (depth == strings.length - 1) {
                res.add(String.valueOf(strings));
                return;
            }
            Set<Character> set = new HashSet<>();//hash容器不与下层递归交互，无需reverse
            // attention start from depth
            for (int i = depth; i < strings.length; i++) {
                if (set.contains(strings[i])) {
                    continue;
                }
                set.add(strings[i]);
                swap(strings, depth, i);
                dfs(depth + 1, strings, res);
                swap(strings, i, depth);
//                set.remove(strings[i]);
            }
        }

        private void swap(char[] strings, int depth, int i) {
            char tmp = strings[depth];
            strings[depth] = strings[i];
            strings[i] = tmp;
        }
    }
}
